package com.ruoyi.system.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import proto.client.ProtoCmd;
import proto.client.UserInfo;

import java.util.Collections;

/**
 * Author:cgChen
 * Date:2022/05/14 15:36
 * Description:
 */
@Service("NettyClient")
public class NettyClient {
    private static Logger log = LoggerFactory.getLogger(NettyClient.class);
    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>(){

                             @Override
                             protected void initChannel(SocketChannel socketChannel) throws Exception {
                                 socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                                 socketChannel.pipeline().addLast(new ProtobufDecoder(ProtoCmd.ResponseCmd.getDefaultInstance()));
                                 socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                                 socketChannel.pipeline().addLast(new ProtobufEncoder());
                                 socketChannel.pipeline().addLast(new NettyClientHandler());
                             }
                         });

        try {
            //47.104.195.177
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
            log.info("客户端成功....");
            //UserInfo.UserMsg.Builder userMsg=UserInfo.UserMsg.newBuilder();
            //userMsg.setAge(17);
            //userMsg.setId(2);
            //userMsg.setName("李四");
            //userMsg.setState(2);
            ////发送消息
            //future.channel().writeAndFlush(userMsg.build());
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}
